<?php

namespace Frontend\Controller;

use Admin\Model\AdminUserMessage;
use Zend\Authentication\Validator\Authentication;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Validator\File\UploadFile;
use Zend\View\Model\ViewModel;
use Admin\Model\AdminUser;
use \Velacolib\Utility\Utility;
use Zend\Form\Form;
use Zend\Form\Element;
use Admin\Model\AdminUserContact;
use Zend\View\ViewEvent;
use Frontend\Helper\SimpleImage;

class UserController extends AbstractActionController
{
    protected $topicModel;
    protected $userModel;
    protected $topicImageModel;
    protected $auth;
    protected $userMessage;
    protected $messageTable;
    protected $userContactTable;
    protected $FriendTable;
    protected $translator;

    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        $this->layout('frontend/layout');

        $this->topicModel = Utility::UserGateway('Admin\Model\AdminTopicTable');
        $this->userModel = Utility::UserGateway('Admin\Model\AdminUserTable');
        $this->topicImageModel = Utility::UserGateway('Admin\Model\AdminTopicImgTable');
        $this->messageTable = UTility::UserGateway('Admin\Model\AdminUserMessageTable');
        //temp delete

        $this->userMessage = Utility::UserGateway('Admin\Model\AdminUserMessageTable');
        $this->userContactTable = Utility::UserGateway('Admin\Model\AdminUserContactTable');
        $this->FriendTable = Utility::UserGateway('Admin\Model\AdminFriendsTable');
        $this->translator = Utility::translate();
        return parent::onDispatch($e);
    }

    public function init()
    {
        //$this->Acl->SetModule('Project');
        //if(!$this->Acl->Check())
        //  $this->redirect()->toRoute('home', array ('action' => 'index'));
    }

    public function messageAction()
    {
        $this->auth = Utility::CheckLogin($this);
        $message_all = $this->userMessage->fetchAll($this->auth->userid);
        $message_all->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
        // set the number of items per page to 10
        $message_all->setItemCountPerPage(ITEM_PER_PAGE);


        $view = new ViewModel(array('message' => $message_all, 'auth' => $this->auth));
        $view->setTerminal(true);
        return $view;
    }

    /*
       public function processregisterAction()
       {


           $response['result'] = false;

           $response['locate'] = '';
           //Ajax function
           if ($this->getRequest()->isPost()) {

               $dataSubmit = $this->params()->fromPost();

               //Check if ajax request is submited
               if (!isset ($dataSubmit['ajax_request']))

                   $this->redirect("/");

               $user_model = new AdminUser();

               $validate = $user_model->validateUserFields($dataSubmit);

               if ($validate['pass']) {

                   $dataSubmit['name'] = $this->params()->fromPost('f_name') . ' ' . $this->params()->fromPost('l_name');

                   $dataSubmit['avatar'] = '';

                   $dataSubmit['status'] = '1';

                   $dataSubmit['user_type'] = '2';

                   $time = time();

                   $dataSubmit['time_reg'] = $time;

                   $dataSubmit['password'] = md5($dataSubmit['email'] . $dataSubmit['password']);

                   unset ($dataSubmit['f_name'], $dataSubmit['l_name'], $dataSubmit['r_password']);

                   $object = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($dataSubmit['email']);

                   if (is_object($object)) {

                       $response['result'] = false;

                       $response['message'] = 'This email already exists';

                   } else {

                       $user_model->exchangeArray($dataSubmit);

                       $addUser = Utility::UserGateway('Admin\Model\AdminUserTable')->saveUser($user_model);

                       if ($addUser) {

                           $response['result'] = true;

                           $response['message'] = 'Successfully registration progress';

                           //sending email verify to user register
                           $smtp_option = array(
                               'smtp_user' => 'mrhungmaster1905@gmail.com',
                               'smtp_password' => '`1qa2ws#ED'
                           );
                           $senderInfo = array(
                               'email' => 'mrhungmaster1905@gmail.com',
                               'name' => ' Nguy?n Thanh H?ng'

                           );

                           $RecipientInfo = array(
                               'email' => $dataSubmit['email'],
                               'name' => $dataSubmit['name'],
                               'link' => 'http://' . $_SERVER['HTTP_HOST'] . '/user/verify/' . $time,
                           );

                           $template_path = 'admin/email/tpl/template';

                           $subject = 'Email Verify';

                           Utility::SendMail(true, $smtp_option, $senderInfo, $RecipientInfo, $template_path, $subject);

                       } else $response['message'] = 'Unable to register new user';
                   }


               } else $response['message'] = $validate['message'];
           } else $response['message'] = 'Method not allowed';
           header("ContentType: application/json");
           echo json_encode($response);
           die();
       }
          */

    public function loginAction()
    {
        $aut = new AuthenticationService();
        if ($aut->hasIdentity() == 1) {
            return $this->redirect()->toRoute('home', array('action' => 'index'));
        }

        $response['result'] = false;

        $response['locate'] = '';

        if ($this->getRequest()->isPost()) {

            $data = $this->params()->fromPost();

            $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');

            $user_table->setLoginUser($data);

            $login_obj = new AuthenticationService(null, $user_table);

            $login_obj->authenticate();

            $test = new AuthenticationService();
            //echo '<pre>';
            ///print_r($login_obj->getIdentity());die;

            if ($test->hasIdentity() == 1) {
                if ($login_obj->getIdentity()->confirm == 0) {
                    $response['result'] = false;
                    $response['message'] = 'Email is not verify ....';
                    $response['email'] = $login_obj->getIdentity()->email;
                    $response['time_reg'] = $login_obj->getIdentity()->time_reg;
                    $response['name'] = $login_obj->getIdentity()->name;
                    $response['confirm'] = 0;
                } else {
                    $response['result'] = true;

                    $response['message'] = 'Login success ....';

                    $response['locate'] = 'http://' . $_SERVER['HTTP_HOST'];
                }

            } else {

                $response['result'] = false;

                $response['message'] = 'Wrong user or password , Please try again!';

            }
            header("ContentType: application/json");

            echo json_encode($response);
            die();
        }

    }

    public function confirmAction()
    {
        $this->auth = Utility::CheckLogin($this);
        $data = array();
        $data = $this->params()->fromPost();
        //sending email verify to user register
        $smtp_option = array(
            'smtp_user' => 'mrhungmaster1905@gmail.com',
            'smtp_password' => '`1qa2ws#ED'
        );
        $senderInfo = array(
            'email' => 'mrhungmaster1905@gmail.com',
            'name' => ' Nguy?n Thanh H?ng'

        );

        $RecipientInfo = array(
            'email' => $data['email'],
            'name' => $data['name'],
            'link' => 'http://' . $_SERVER['HTTP_HOST'] . '/user/verify/' . $data['time_reg'],
        );

        $template_path = 'admin/email/tpl/template';

        $subject = 'Email Verify';

        Utility::SendMail(true, $smtp_option, $senderInfo, $RecipientInfo, $template_path, $subject);

    }

    public function verifyAction()
    {

        $response['result'] = false;

        $response['locate'] = '';

        $time = $this->params()->fromRoute('id', 0);

        if ($this->getRequest()->isPost()) {

            $data = $this->params()->fromPost();

            $userData = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($data['email']);

            if (is_object($userData)) {

                $save = array(
                    'confirm' => 1
                );

                Utility::UserGateway('Admin\Model\AdminUserTable')->save($save, $where = array('email' => $data['email']));

                $response['result'] = true;

                $response['message'] = 'verify email success ....';

                $response['locate'] = 'http://' . $_SERVER['HTTP_HOST'];


            } else {
                $response['result'] = false;

                $response['message'] = 'Email invalid.....';

            }

            header("ContentType: application/json");

            echo json_encode($response);
            die;

        }
        return new ViewModel(array(
            'time' => $time,
        ));

    }

    public function profileAction()
    {
        $this->auth = Utility::CheckLogin($this);
        $response['result'] = false;
        $response['locate'] = '';
        $auth = new AuthenticationService();
        $user = $auth->getIdentity();
        $userInfo = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($auth->getIdentity()->email);
        $where = array();

        if ($this->request->isPost()) {

            $postArr = $this->request->getPost()->toArray();

            if(! isset($postArr['zalo'])) $postArr['zalo'] = 0;
            if(! isset($postArr['viber'])) $postArr['viber'] = 0;
            if(! isset($postArr['kakaotalk'])) $postArr['kakaotalk'] = 0;

            $file = $this->params()->fromFiles('avatar');
            if (($file['name'] != '')) {
                $simple_image = new SimpleImage($file['tmp_name']);
                $time = time();
                $simple_image->save("./public/img/upload/user_temp/" . $time . $file['name']);
                $files['avatar'] = '/img/upload/user_temp/' . $time . $file['name'];
                $postArr['id'] = $user->userid;
                $saveuser = array_merge($postArr, $files);
            } else {
                $saveuser = $postArr;
            }


            Utility::UserGateway('Admin\Model\AdminUserTable')->save($saveuser, array('id' => $userInfo->id));
            $userInfo = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($auth->getIdentity()->email);
            return new ViewModel(array(
                'auth' => $userInfo,
                'status' => 1,

            ));

        }

        return new ViewModel(array(
            'auth' => $userInfo,

        ));


    }

    function logoutAction()
    {
        $auth = new AuthenticationService();
        $auth->clearIdentity();
        return $this->redirect()->toRoute('home', array(
            'controller' => 'index',
            'action' => 'index',
        ));
    }

    function aboutAction()
    {
        $this->auth = Utility::CheckLogin($this);
        $userid = $this->params()->fromRoute('param', 0);
        $users = $this->userModel->getUser($userid);
        return new ViewModel(array(
            'user' => $users,
        ));


    }

    /* changpass function*/

    public function changepassAction()
    {
        $result = array(
            'notice_repass' => true,
            'notice_pass' => true,
            'notice_result' => false
        );
        if ($this->request->isPost()) {
            $changepassData = $this->params()->fromPost();
            if ($changepassData['password'] != $changepassData['repassword']) {
                $result['notice_repass'] = false;
            } else {
                unset($changepassData['repassword']);
                $rs = $this->userModel->changeUserPass($changepassData);
                $result['notice_pass'] = $rs;
                $result['notice_result'] = $rs;
            }
        }
        return new ViewModel(array(
            'result' => $result
        ));

    }

    function topicAction()
    {

        $view = $this->params()->fromQuery('view');
        $user_id = $this->params()->fromRoute('param', 0);
        $auth = new AuthenticationService();
        $search_title = null;
        if (isset($_GET['q'])) {
            $search_title = $this->params()->fromQuery('q');
            ($search_title != '') ? $search_title = $search_title : $search_title = null;

        }
        (isset($_GET['is_p'])) ? $where['is_public'] = $_GET['is_p'] : $where[] = 'is_public = "yes"';


        $paging = $this->topicModel->getTopicByUser($auth->getIdentity()->userid, true, $search_title, $where);
        $paging->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
        // set the number of items per page to 10
        $paging->setItemCountPerPage(ITEM_PER_PAGE);
        $user = $this->userModel->getUser($user_id);
        $is_p = $this->params()->fromQuery('is_p');
        if ($is_p == '') $is_p = 'yes';

        $dataReturn = array(
            'topics' => $paging,
            'param' => $user_id,
            'user' => $user,
            'auth' => $auth,
        );

        $dataReturn['search_val']['is_p'] = $is_p;

        $return = new ViewModel($dataReturn);

        return $return;
    }

    function addfriendAction()
    {
        $userid = $_POST['id'];
        echo $userid;
        die;
    }

    public function searchAction()
    {

        $request = $this->getRequest();
        if (!$request->isXmlHttpRequest()) {
            $search_val = $this->params()->fromQuery('search_val');
            $user_array = $this->userModel->searchFullText($search_val);
            $user_array->setItemCountPerPage(ITEM_PER_PAGE);
            $topic_array = $this->topicModel->searchFullText($search_val);
            $topic_array->setItemCountPerPage(ITEM_PER_PAGE);

            $return_array = array();
            $return_array['user'] = $user_array;
            $return_array['topic'] = $topic_array;
            $return_array['search_val'] = $search_val;
            return new ViewModel($return_array);
        } else {
            $search_val = $this->params()->fromQuery('search_val');
            $user_array = $this->userModel->searchFullTextArray($search_val);
            $topic_array = $this->topicModel->searchFullTextArray($search_val);

            $return_array = array();
            $return_array['user'] = $user_array;
            $return_array['topic'] = $topic_array;

            echo json_encode($return_array);
            die;
        }
    }

    public function friendlistAction()
    {
        $auth = new AuthenticationService();
        $loginId = $auth->getIdentity()->userid;
        $friendTable = Utility::UserGateway('Admin\Model\AdminFriendsTable');
        $friendList = $friendTable->fetchAll($loginId);
        $arr = array();
        foreach ($friendList as $friend) {
            $arr[] = $friend;
        }
        return array('friends' => $arr, 'user_id' => $loginId);

        //header("ContentType: application/json");
        //echo json_encode($arr);
        //die;
    }

    public function inboxAction()
    {
        $user = UTility::CheckLogin($this, '/login');
        $message = new AdminUserMessage();
        $to_user = $this->params()->fromRoute('param');
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = $this->params()->fromPost();
            //die;
            //$to_user = $data['to_user'];
            $data['form_user'] = $user->userid;
            $data['from_user_name'] = $user->name;
            $data['type_request'] = '1';
            $data['create_date'] = date("Y-m-d H:i:s");
            unset($data['submit']);
            $message->exchangeArray($data);
            $is_sent = $this->messageTable->saveAddMessage($message);
            die;
            return array('to_user' => $to_user, 'is_sent' => $is_sent);
        }
        die;
        return array('to_user' => $to_user);
    }

    public function UserSearchProfileAction()
    {
        $Auth_service = new AuthenticationService();
        $auth = $Auth_service->getIdentity();

        $id = $this->params()->fromRoute('param');
        $user = $this->userModel->getUser($id);
        return new ViewModel(array('user' => $user, 'auth' => $auth));

    }

    public function getFriendMessageAction()
    {
        $auth = new AuthenticationService();
        $loginId = $auth->getIdentity()->userid;
        $friend_id = $this->params()->fromQuery('friend_id');
        $array_message = $this->userMessage->fetchFriendMessage($loginId, $friend_id, 0, 10000);

        $view = new ViewModel(array('data' => $array_message, 'user_id' => $loginId));
        $view->setTerminal(true);
        return $view;

    }

    public function updateMessageStatusAction()
    {
        $auth = new AuthenticationService();
        $loginId = $auth->getIdentity()->userid;
        if (!isset($loginId)) {
            return '';
            die;
        }

        if ($this->getRequest()->isPost()) {

            $message_id = $this->params()->fromPost('message_id');
            $message_info = $this->messageTable->getMessage($message_id);
            $message_info->is_accepted = 1;
            $this->messageTable->saveAddMessage($message_info);
        }
        die;

    }

    public function getFriendTopicAction()
    {
        $friend_topics = array();
        $auth = new AuthenticationService();
        $loginId = $auth->getIdentity()->userid;
        if (!isset($loginId)) {
            return '';
            die;
        }
        // Find out how many items are in the table
        $total = $this->FriendTable->getFriendTopic($loginId, 0, 1000);
        $total = count($total);
        // How many items to list per page
        $limit = 5;
        // How many pages will there be
        $pages = ceil($total / $limit);

        //current page
        $page = $this->params()->fromQuery('page');
        // Calculate the offset for the query
        $offset = ($page - 1) * $limit;
        // Some information to display to the user

        $start = $offset;
        $end = min(($offset + $limit), $total);


        if ($page < $pages) {
            $friend_topics = $this->FriendTable->getFriendTopic($loginId, $start, $end);

        }

        // $friend_topics = $this->FriendTable->getFriendTopic($loginId,0,5);
        $view = new ViewModel(array('friend_topics' => $friend_topics));
        $view->setTerminal(true);
        return $view;
    }

    public function forgotpasswordAction()
    {

        $view = new ViewModel();
        $view->setTemplate("frontend/user/forgotpass.phtml");
        return $view;
    }

}